<?php

declare(strict_types=1);

namespace NanQi\Hope\Exception\Handler;

use Elasticsearch\Common\Exceptions\Missing404Exception;
use NanQi\Hope\Constants\StatusCodeConstants;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class EsNotFoundExceptionHandler extends BaseExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->stopPropagation();

        /** @var Missing404Exception $throwable */
        $data = json_decode($throwable->getMessage(), true);
        $data['trace'] = $throwable->getTrace();
        return $this->errorResponse($response,
            StatusCodeConstants::S_404_NOT_FOUND,
            "没有找到对应的索引或ID", $data);
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof Missing404Exception;
    }
}
